package com.edou.auth.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.json.simple.JSONObject;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

import com.edou.auth.entity.User;
import com.edou.auth.form.UserForm;
import com.edou.auth.service.IDepartService;
import com.edou.auth.service.IRightService;
import com.edou.auth.service.IUserService;
import com.edou.base.controller.BaseController;

/**
 * 用户管理controller
 * @creator     admin
 * @create-time 2016年2月15日   上午10:25:50
 * @email admin@edou.com
 * @company www.edou.com
 * @version 1.0
 */
@Controller("userController")
@Scope("prototype")
@RequestMapping(value = "/admin/auth/user")
public class UserController extends BaseController {
	
	@Resource(name = "userServiceImpl")
	private IUserService userService;
	@Resource(name = "departServiceImpl")
	private IDepartService departService;
	@Resource(name = "rightServiceImpl")
	private IRightService rightService;
	
	/**
	 * 用户管理
	 * @return
	 */
	@RequestMapping(value = "/index.htm", method = RequestMethod.GET)
	public ModelAndView index(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/auth/user_list");
		
		return view;
	}
	
	/**
	 * 分页查询用户
	 * @return
	 */
	@RequestMapping(value = "/listUserByPage.htm", method = RequestMethod.POST)
	public void listUserByPage(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try{
			userService.listUserByPage(model.getPageResult(), model.getCondition());
			JSONObject root = toPageJson(model.getPageResult(), new String[]{"id","staffId","name","sex","birthday","mobile","tel","email","contact","account","password","state","onlineState","isChangePwd","roleNames","departNames","isManager"});
			ajaxPageResult(root,response);
		}catch(Exception ex){
			String msg = "查询用户时发生异常："+ex.getMessage();
			logger.error(msg,ex);
		}
	}
	
	/**
	 * 跳转到新增或修改用户页面
	 * @return
	 */
	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public ModelAndView edit(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response){
		ModelAndView view = new ModelAndView();
		Map<String, Object> data=view.getModel();
		view.setViewName("/admin/auth/user_add");
		
		if(StringUtils.isNotBlank(model.getItem().getId())){
			User item = userService.getUserDetailById(model.getItem().getId());
			data.put("item", item);
		}
		
		return view;
	}
	
	/**
	 * 保存用户
	 * @return
	 */
	@RequestMapping(value = "/saveUser.htm", method = RequestMethod.POST)
	public ModelAndView saveUser(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response){
		try {
			User currentUser = userService.getCurrentUser();
			model.getItem().setCreateBy(currentUser.getAccount());
			model.getItem().setUpdateBy(currentUser.getAccount());
			
			userService.saveUser(model.getItem());
			return ajaxJSON(Status.success,"保存成功");
		} catch (Exception e) {
			String msg = "保存用户时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error,"保存失败");
		}
	}
	
	@RequestMapping(value = "/changeState.htm", method = {RequestMethod.POST,RequestMethod.GET})
	public ModelAndView changeState(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response){
		ModelAndView view = new ModelAndView();
		view.setViewName("/admin/auth/user_state");
		Map<String, Object> data = view.getModel();
		User user = userService.getUserByAccount(model.getItem().getAccount());
		data.put("item", user);
		return view;
	}
	
	/**
	 * 修改用户状态
	 */
	@RequestMapping(value = "/updateState.htm", method = RequestMethod.POST)
	public ModelAndView updateState(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response){
		try {
			User currentUser = userService.getCurrentUser();
			model.getItem().setUpdateBy(currentUser.getAccount());
			
			userService.updateState(model.getItem());
			return ajaxJSON(Status.success,"修改成功");
		} catch (Exception e) {
			String msg = "修改用户状态时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error,"修改失败");
		}
	}
	
	
	/**
	 * 重置密码
	 * @return
	 */
	@RequestMapping(value = "/resetPwd.htm", method = RequestMethod.POST)
	public ModelAndView resetPwd(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response){
		try {
			User currentUser = userService.getCurrentUser();
			model.getItem().setUpdateBy(currentUser.getAccount());
			
			userService.resetPwd(model.getItem());
			return ajaxJSON(Status.success,"重置成功");
		} catch (Exception e) {
			String msg = "重置密码时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error,"重置失败");
		}
	}
	
	
	/**
	 * 删除用户
	 * @return 
	 */
	@RequestMapping(value = "/del.htm", method = RequestMethod.POST)
	public ModelAndView del(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response,HttpSession session){
		try {
			userService.delByIds(model.getSelIds().split(","));
			return ajaxJSON(Status.success,"删除成功");
		} catch (Exception e) {
			String msg = "删除用户时发生异常：" + e.getMessage();
			logger.error(msg,e);
			return ajaxJSON(Status.error, "删除失败，请稍后重试");
		}
	}
	

	/**
	 * 弹出选择角色页面
	 * @return
	 */
	@RequestMapping(value = "/choose_role.htm", method = RequestMethod.GET)
	public String chooseRole(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response){
		return "/admin/auth/user_choose_role";
	}
	
	/**
	 * 导入
	 * @return
	 */
	@RequestMapping(value = "/import.htm", method = RequestMethod.POST)
	public ModelAndView doImport(@ModelAttribute UserForm model,HttpServletRequest request,HttpServletResponse response){
		MultipartHttpServletRequest multipartRequest  =  (MultipartHttpServletRequest) request;
	    MultipartFile uploadFile = multipartRequest.getFile("uploadFile");
	    if (uploadFile == null) {
            return ajaxJSON(Status.error,"上传失败：文件为空",true,request);
        }
	    try {
	    	User currentUser = userService.getCurrentUser();
	    	String path = this.doUploadFile(uploadFile,"/upload",request);
	    	String realPath = request.getSession().getServletContext().getRealPath(path);
	    	String errorIndex =userService.doImport(realPath,currentUser.getAccount());
	    	return ajaxHTML(Status.success, errorIndex, null);
		} catch (Exception e) {
			e.printStackTrace();
			String msg   = "上传文件失败："+e.getMessage();
			logger.info(msg);
			return ajaxHTML(Status.error,"导入失败",null);
		}
	}
	
	/**
	 * 用户批量移动部门
	 */
	@RequestMapping(value = "/doMove.htm", method = RequestMethod.POST)
	public ModelAndView doMove(@ModelAttribute UserForm model,HttpServletRequest request){
		try{
			User user = userService.getCurrentUser();
			userService.doMoveDepart(model.getSelIds(),model.getOldDepartId(), model.getNewDepartId(), user.getAccount());
			return ajaxJSON(Status.success,"移动成功");
		}catch(Exception ex){
			String msg = "更换部门时发生异常：" + ex.getMessage();
			logger.error(msg,ex);
			
			return ajaxJSON(Status.error,"移动失败，请稍后重试");
		}
	}
	
	/**
	 * 设置主管
	 */
	@RequestMapping(value = "/updateManager.htm", method = RequestMethod.POST)
	public ModelAndView updateManager(@ModelAttribute UserForm model,HttpServletRequest request){
		try{
			userService.updateManager(model.getItem());
			return ajaxJSON(Status.success,"设置主管成功");
		}catch(Exception ex){
			String msg = "设置主管时发生异常：" + ex.getMessage();
			logger.error(msg,ex);
			return ajaxJSON(Status.error,"设置主管失败，请稍后重试");
		}
	}
	
	/**
	 * 根据名称查询用户
	 * 
	 * @return
	 */
	@SuppressWarnings("static-access")
	@RequestMapping(value = "/listUserCondition.htm")
	public void listUserByCondition(@ModelAttribute UserForm model, HttpServletResponse response) {

		List<User> list = userService.listUserByCondition(model.getCondition());
		JSONObject result = this.toJsonResultList(list, new String[] {"id", "name", "staffId" });
		ajaxPageResult(result, response);
	}
	
}
